package com.xframe.xdal.core.model.sqlbuilder.proc;


import com.xframe.xdal.core.constant.DalConstants;
import com.xframe.xdal.core.model.mapping.IColumnMapping;
import com.xframe.xdal.core.model.mapping.ITableInfo;
import com.xframe.xdal.core.model.sqlbuilder.BaseSqlBuilder;
import com.xframe.xdal.core.model.sqlbuilder.BuilderContext;
import com.xframe.xdal.core.model.sqlbuilder.SqlExpression;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述：删除sql 构造器 PK
 * 创建人：xufeng
 * 创建时间：2022/10/8 9:49
 *
 * @version 1.0
 **/

public class DeleteSqlBuilder extends BaseSqlBuilder {
    /**
     * 删除 sql 语句
     *
     * @return 返回sql语句
     */
    public String getSQL() {
        return " delete from %s where %s ";
    }

    /**
     * 构造根据pk删除sql语句
     *
     * @param context 上下文
     * @return SqlExpression
     */
    @Override
    public SqlExpression build(BuilderContext context) {
        ITableInfo tableInfo = context.getTableInfo();
        IColumnMapping pk = context.findPkFirst();
        List<Object> paramList = new ArrayList<>();
        paramList.add(context.getData().getObjectFieldValue(pk.getFieldName()));
        StringBuilder dsb = new StringBuilder(context.getNameConvert().toName(pk.getName()));
        dsb.append(DalConstants.SQL_EQUAL);
        dsb.append(DalConstants.SQL_PLACE_HOlDER);
        String deleteSql = String.format(getSQL(), context.getNameConvert().toName(tableInfo.getName()), dsb);
        return new SqlExpression(deleteSql, paramList,context.getDataSourceTypeEnums());
    }
}
